<?php

namespace DP\EventBundle\Form;

use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManager;
use DP\EventBundle\Entity\Event;

class EventHandler
{
    protected $obj_form;
    protected $obj_request;
    protected $obj_em;

    public function __construct(Form $obj_form, Request $obj_request, EntityManager $obj_em)
    {
        $this->obj_form    = $obj_form;
        $this->obj_request = $obj_request;
        $this->obj_em      = $obj_em;
    }

    public function process()
    {
        if( $this->obj_request->getMethod() == 'POST' )
        {
            $this->obj_form->bindRequest($this->obj_request);

            if( $this->obj_form->isValid() )
            {
                $this->onSuccess($this->obj_form->getData());

                return true;
            }
        }

        return false;
    }

    public function onSuccess(Event $obj_event)
    {
        $this->obj_em->persist($obj_event);
        
        // On persiste tous les tags de l'événement.
        foreach ($obj_event->getTags() as $tag)
        {
        	$this->obj_em->persist($tag);
        }
        
        $this->obj_em->flush();
    }
}
